package service;

import java.io.File;
import java.io.IOException;

import data.AppConstants;

public class FileService 
{
	
	private String pathToRepository;
	private String fileTitle = "";
	private String directory = "";
	
	// ********************************************************************************************************** start
    // ** public methods ***	
	
	/**
	 * @param args
	 * @return String pathToRepository
	 */
	public String getPathToRepository(String[] args)
	{

		if (args.length > 0 )
		{
			pathToRepository = args[0];
			String[] nameDirectory = pathToRepository.split(AppConstants.SEPARATOR);

			for (int i = 0; i < nameDirectory.length ; i++)
			{
				if ( !nameDirectory[i].contains(AppConstants.EXTENSION))
				{
					directory = directory + nameDirectory[i] + AppConstants.SEPARATOR;
				}
				else
				{				
					fileTitle = nameDirectory[i];
				}
			}
		
			if (!checkFile())
			{
				checkDirectory();
			}
		}
		else			
		{
			pathToRepository = AppConstants.FULL_PATH;
		}
		
		return pathToRepository;
		
	}
	
	// ********************************************************************************************************** end
	
	// ********************************************************************************************************** start
    // ** private metods ***	
	
	private Boolean checkFile()
	{

		File checkingFile = new File(pathToRepository);
		
		if (checkingFile.isFile())
		{
			System.out.println("It is File");
			
			return true;
		}
		
		if (!fileTitle.isEmpty() && directory.isEmpty())
		{
			pathToRepository = fileTitle;
			File file = new File(pathToRepository);
			try 
			{
				file.createNewFile();
			} catch (IOException e) 
			{
				System.out.println("Sorry, but file does not create :(");
				pathToRepository = AppConstants.PATH_TO_FILE;
			}
			
			return true;
		}
		
		return false;

	}

	private void checkDirectory()
	{

		File checkingDirectory = new File(directory);

		if (checkingDirectory.isDirectory())
		{
			System.out.println("It is Directory");
			String personPathDefoltTitle;
			if (fileTitle.isEmpty())
			{
				personPathDefoltTitle = directory + AppConstants.FILE_TITLE;
			}
			else
			{
				personPathDefoltTitle = directory + fileTitle;
			}
			
			File file = new File(personPathDefoltTitle);					
			try 
			{
				file.createNewFile();
				pathToRepository = personPathDefoltTitle;
			} catch (IOException e) 
			{
				System.out.println("Sorry, but file does not create :(");
				pathToRepository = AppConstants.PATH_TO_FILE;
			}
		}
		else
		{
			System.out.println("Directory not found. Exit...");
			System.exit(0);
		}

	}
	
	// ********************************************************************************************************** end


}